package com.test.activiti.activiti.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.test.activiti.activiti.mapper.ActRuTaskMapper;
import com.test.activiti.activiti.po.ActRuTaskPO;
import com.test.activiti.activiti.vo.PageResponse;
import com.test.activiti.activiti.vo.TaskVO;
import com.test.activiti.util.PageUtils;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.runtime.ProcessInstance;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Author dzf62
 * @Description TODO
 * @Date 2023/9/4 20:11
 * @Version 1.0
 */
@Component
public class RuTaskService {
    @Autowired
    ActRuTaskMapper taskMapper;
    @Autowired
    RuntimeService runtimeService;
    @Autowired
    RepositoryService repositoryService;

    public PageResponse<TaskVO> taskList(int page, int pageSize){
        PageHelper.startPage(page, pageSize);
        List<ActRuTaskPO> actRuTaskPOS = taskMapper.taskList();
        List<ProcessInstance> list = runtimeService.createProcessInstanceQuery().processInstanceIds(actRuTaskPOS.stream().map(ActRuTaskPO::getProcInstId).collect(Collectors.toSet())).list();
        Map<String, ProcessInstance> processInstanceMap = list.parallelStream().collect(Collectors.toMap(ProcessInstance::getProcessInstanceId, processInstance -> processInstance));
        List<TaskVO> voList = actRuTaskPOS.parallelStream().map(po -> {
            TaskVO taskVO = new TaskVO();
            taskVO.setId(po.getId())
                    .setName(po.getName())
                    .setAssignee(po.getAssignee())
                    .setCreatedTime(po.getCreateTime())
                    .setProcInstId(po.getProcInstId())
                    .setProcDefId(po.getProcDefId())
                    .setProcessName(processInstanceMap.get(po.getProcInstId()).getProcessDefinitionName());
            return taskVO;
        }).collect(Collectors.toList());
        PageInfo<TaskVO> pageInfo = new PageInfo<>(voList);
        return PageUtils.getPageResult(pageInfo);
    }
}
